package name.ekr.edu.threads.chatserver.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EchoConnectionHandler implements ConnectionHandler {
	private static Logger logger = LoggerFactory.getLogger(EchoConnectionHandler.class);
	private Collection<Connection> connections = new HashSet<>();  
	
	@Override
	public void handle(Connection connection) {
		try(	BufferedReader connectionReader = connection.getConnectionReader();
			PrintWriter connectionWriter = connection.getConnectionWriter()) {
			
			connections.add(connection);
			logger.info("Users online " + connections.size());
			String stringFromConnection;
			do {
				stringFromConnection = connectionReader.readLine();
				if(stringFromConnection == null) throw new IOException("Connection closed");
				logger.info("Recieved message " + stringFromConnection);
				
				for (Connection c : connections) {
					c.getConnectionWriter().println(stringFromConnection);
				}
			} while (! ("quit".equals(stringFromConnection) || Thread.interrupted()) );
			
		} catch (IOException e) {
			logger.error("", e);
			throw new RuntimeException("Communication error", e);
		} finally {
			connections.remove(connection);	
			logger.info("Users online " + connections.size());
		}
	}
}
